package com.example.base.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class TextEncryptUtils {


    public static SecretKey generateAesKey() {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(128); // 生成128位的AES密钥
            return keyGen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String keyToString(SecretKey key) {
        byte[] keyBytes = key.getEncoded();
        return Base64.getEncoder().encodeToString(keyBytes);
    }

    public static SecretKey stringToKey(String keyStr) {
        byte[] keyBytes = Base64.getDecoder().decode(keyStr);
        return new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
    }

    public static String encryptText(String text, SecretKey key) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedBytes = cipher.doFinal(text.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryptText(String encryptedText, SecretKey key) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
      //  SecretKey aesKey = generateAesKey();
    //   String key= keyToString(aesKey);
       // System.out.println(key);

       SecretKey aesKey =stringToKey("OVMG715RY4ja49f+5V/4YA==");
        String originalText = "Hello, World!";
        String encryptedText = encryptText(originalText, aesKey);
        System.out.println("Encrypted Text: " + encryptedText);
        encryptedText="k5VEqN4+1z82ogrqUAkOaA==";
        String decryptedText = decryptText(encryptedText, aesKey);
        System.out.println("Decrypted Text: " + decryptedText);
    }
}
